<template>
  <div class="upload-box">
    <el-upload
      :on-preview="preview"
      :on-remove="hangmove"
      :file-list="fileList"
      list-type="picture-card"
      :limit="2"
      action="#"
      :on-change="onchang"
      :class="{disabled: fileComputed }"
      :http-request="httprequest"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog width="600px" top="8vh" title="图片预览" :visible.sync="showDialog">
      <img width="100%" :src="imgUrl" alt="">
    </el-dialog>
    <div v-if="showProgress">
      <div>上传进度：<el-progress style="width: 180px;" :percentage="percent" /></div>
    </div>
  </div>
</template>

<script>
import cos from '@/utils/cos'
export default {
  data() {
    return {
      fileList: [],
      showDialog: false, // 控制显示弹层
      imgUrl: ''
    }
  },
  computed: {
    // 设定一个计算属性 判断是否已经上传完了一张
    fileComputed() {
      return this.fileList.length >= 2
    }
  },
  methods: {
    beforeUpload(file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    },
    onchang(file, fileList) {
      this.fileList = [...fileList]
    },
    httprequest({ file }) {
      const fileObj = this.fileList.find(item => item.uid === file.uid)
      fileObj.status = 'uploading'
      cos.uploadFile({
        Bucket: 'hass-27-1317277690', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, /* 文件名 */
        // StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5,
        onProgress: (progressData) => {
          fileObj.percentage = progressData.percent * 100
        }
      }, function(err, data) {
        if (err) {
          console.log('上传失败', err)
        } else {
          // 更新状态
          fileObj.status = 'success'
          // 修改地址
          fileObj.url = 'https://' + data.Location
        }
      }
      )
    },
    preview(file) {
      // 这里应该弹出一个层 层里是点击的图片地址
      this.imgUrl = file.url
      this.showDialog = true
    },
    hangmove(file, filelist) {
      console.log(file, filelist)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
